<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Menu;
use App\Models\Role;
use Symfony\Component\HttpKernel\Exception\HttpException;

class RoleController extends Controller
{
    // 初始化保存模型
    protected function initialize()
    {
        $this->model = new Role();
    }

    public function index(Request $request)
    {
        $page = $request->query('page', 1);
        $pageSize = $request->query('pageSize', 10);

        $model = $this->model::paginate(
            (int)$pageSize,
            ['*'], // 获取哪些字段，* 表示获取全部
            'page',
            (int)$page
        );
        return $this->successList(list: $model->items(), total: $model->total());
    }

    public function store(Request $request)
    {
        $body = $request->json()->all();
        try {
            $model = $this->model::create($body);
            return $this->success(data: ['id' => $model->id]);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function update($id, Request $request)
    {
        $body = $request->json()->all();
        try {
            $this->model::where('id', $id)->update($body);
            return $this->success(message: '修改成功');
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function destroy($id)
    {
        try {
            $this->model::destroy($id);
            return $this->success(message: '删除成功');
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function getRoleMenu()
    {

        $menu = Menu::select('parentId', 'id', 'menuType', 'title')->get();

        return $this->success(data: $menu->toArray());
    }

    public function getRoleMenuIds($id)
    {
        $model = $this->model::where('id', $id)->select('menuIds')->first();
        return $this->success(data: array_map(function ($value) {
            return  (int) $value;
        }, explode(',', $model->menuIds)));
    }

    public function setRoleMenuIds(Request $request)
    {
        $id = $request->json('id');
        $ids = $request->json('ids');
        try {
            $this->model->where('id', $id)->update([
                'menuIds' => $ids
            ]);
            return $this->success(message: '修改成功');
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }
}
